package com.hunan.chinamobile.task;

import com.hunan.chinamobile.model.Device;
import com.hunan.chinamobile.model.DeviceData;
import com.hunan.chinamobile.service.DeviceDataService;
import com.hunan.chinamobile.service.DeviceService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

@Component
public class DeviceStatusTask {

    @Resource
    private DeviceService deviceService;
    @Resource
    private DeviceDataService deviceDataService;


    @PostConstruct
    public void updateDeviceLineStatus(){
        runTask();
    }

    private void runTask(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    List<Device> deviceList = deviceService.findAll();
                    if(deviceList != null && deviceList.size() > 0){
                        for(Device d : deviceList){
                            List<DeviceData> dds = deviceDataService.findByDeviceId(d.getDeviceId());
                            boolean isTrue = true;
                            if(dds != null && dds.size() > 0 ){
                                long currDeviceTime = dds.get(0).getCreatedAt().getTime();
                                if((System.currentTimeMillis() - currDeviceTime) <= 24 * 60 * 60 * 1000){
                                    isTrue = false;
                                }
                            }
                            if(isTrue){
                                deviceService.updateOnlineByOneNetId(0,d.getOneNetId());
                            }
                        }
                    }
                    try {
                        Thread.sleep(1000 * 60 * 60);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
